package cn.codeforfun.initialization.command;

import cn.codeforfun.initialization.utils.JschUtil;
import com.jcraft.jsch.JSchException;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.codeforfun.initialization.command.CommandConstants.*;

/**
 * @author wangbin
 */
@Service
public class CommandService {

    /**
     * 获取系统版本
     */
    public Map<String, Object> getSystemVersion(JschUtil jsch) throws JSchException {
        List<String> resultList = jsch.execute(COMMAND_SYSTEM_VERSION);
        if (resultListNull(resultList)) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>(0);
        if (!ObjectUtils.isEmpty(resultList) && resultList instanceof ArrayList) {
            for (String s : resultList) {
                if (ObjectUtils.isEmpty(s)) {
                    continue;
                }
                String[] split = s.split("=");
                String name = split[0];
                String value = split[1];
                if (value.startsWith("\"")) {
                    value = value.substring(1);
                }
                if (value.endsWith("\"")) {
                    value = value.substring(0, value.length() - 1);
                }
                resultMap.put(name, value);
            }
        }
        return resultMap;
    }

    /**
     * 获取系统内核版本
     */
    public String getKernelVersion(JschUtil jsch) throws JSchException {
        String result = null;
        List<String> resultList = jsch.execute(COMMAND_KERNEL_VERSION);
        if (resultListNull(resultList)) {
            return null;
        }
        if (!ObjectUtils.isEmpty(resultList) && resultList.size() == 1) {
            result = resultList.get(0);
        }
        return result;
    }

    /**
     * 获取计算机上的docker版本
     */
    public String getDockerVersion(JschUtil jsch) throws JSchException {
        List<String> resultList = jsch.execute(COMMAND_DOCKER_INFO);
        if (ERROR_MESSAGE_DOCKER_NOT_RUNNING.equals(resultList.get(resultList.size() - 1))) {
            centOsStartDocker(jsch);
            resultList = jsch.execute(COMMAND_DOCKER_INFO);
        }
        Map<String, Object> resultMap = new HashMap<>(0);
        if (resultListNull(resultList)) {
            return null;
        }
        for (String s : resultList) {
            String[] split = s.split(": ");
            if (split.length == 2) {
                resultMap.put(split[0], split[1]);
            }
        }
        String dockerVersion = (String) resultMap.get(" Server Version");
        if (ObjectUtils.isEmpty(dockerVersion)) {
            dockerVersion = (String) resultMap.get("Server Version");
        }

        return dockerVersion;
    }

    /**
     * 获取计算机上的helm版本
     */
    public String getHelmVersion(JschUtil jsch) throws JSchException, JSONException {
        List<String> resultList = jsch.execute(COMMAND_HELM_VERSION);
        if (resultListNull(resultList)) {
            return null;
        }
        String result = resultList.get(resultList.size() - 1);
        String replace = result.replace("Client: &version.Version", "");
        JSONObject jsonObject = new JSONObject(replace);
        return jsonObject.getString("SemVer");
    }

    /**
     * 获取计算机上的kubectl
     */
    public String getKubectlVersion(JschUtil jsch) throws JSchException, JSONException {
        List<String> resultList = jsch.execute(COMMAND_KUBECTL_VERSION);
        if (resultListNull(resultList)) {
            return null;
        }
        String result = resultList.get(resultList.size() - 1);
        String replace = result.replace("Client Version: version.Info", "");
        JSONObject jsonObject = new JSONObject(replace);
        return jsonObject.getString("GitVersion");
    }

    private boolean resultListNull(List<String> resultList) {
        return CollectionUtils.isEmpty(resultList) || resultList.get(0).contains(ERROR_MESSAGE_COMMAND_NOT_FOUND);
    }

    /**
     * 安装docker
     */
    public void installDocker(JschUtil jsch) throws JSchException {
        jsch.execute(COMMAND_INSTALL_DOCKER, 60000);
    }

    /**
     * 安装kubectl
     */
    public void installKubectl(JschUtil jsch) throws JSchException {
        //查询当前版本
        List<String> result = jsch.execute(KUBECTL_VERSION);
        String version = result.get(0);
        String fileName = KUBECTL_FILE_NAME.replace("${KUBECTL_VERSION}", version);
        //删除之前的文件
        String deleteFile = COMMAND_DELETE_FILE.replace("${FILE_NAME}", fileName);
        jsch.execute(deleteFile);
        //下载新文件
        String fileUrl = KUBECTL_URL.replace("${KUBECTL_FILE_NAME}", fileName);
        String downloadUrl = COMMAND_DOWNLOAD_FILE.replace("${FILE_URL}", fileUrl);
        jsch.execute(downloadUrl, 60000);
        //移动到bin目录
        String targetFileName = "/usr/local/bin/kubectl";
        String moveFileCommand = COMMAND_MOVE_FILE.replace("${SOURCE_PATH}", fileName).replace("${TARGET_PATH}", targetFileName);
        jsch.execute(moveFileCommand);
        //增加可执行权限
        String addAuthority = COMMAND_ADD_AUTHORITY.replace("${FILE_PATH}", targetFileName);
        jsch.execute(addAuthority);
    }

    /**
     * 安装helm
     */
    public void installHelm(JschUtil jsch) throws JSchException {
        //获取当前版本
        List<String> result = jsch.execute(HELM_VERSION);
        String version = result.get(0);
        String zipName = HELM_FILE_NAME.replace("${HELM_VERSION}", version);
        //删除之前的文件
        String deleteFile = COMMAND_DELETE_FILE.replace("${FILE_NAME}", zipName);
        jsch.execute(deleteFile);
        //下载新文件
        String fileUrl = HELM_URL.replace("${HELM_FILE_NAME}", zipName);
        String downloadUrl = COMMAND_DOWNLOAD_FILE.replace("${FILE_URL}", fileUrl);
        jsch.execute(downloadUrl, 60000);
        //解压文件
        String unzip = UNZIP_TAR.replace("${FILE_NAME}", zipName);
        jsch.execute(unzip, 10000);
        //移动到bin目录
        String targetFileName = "/usr/local/bin/helm";
        String moveFileCommand = COMMAND_MOVE_FILE.replace("${SOURCE_PATH}", HELM_FOLDER_NAME + "/helm").replace("${TARGET_PATH}", targetFileName);
        jsch.execute(moveFileCommand);
        //增加可执行权限
        String addAuthority = COMMAND_ADD_AUTHORITY.replace("${FILE_PATH}", targetFileName);
        jsch.execute(addAuthority);
        //删除下载的压缩包和解压之后的目录
        String deleteAll = COMMAND_DELETE_FILE.replace("${FILE_NAME}", zipName + " " + HELM_FOLDER_NAME);
        jsch.execute(deleteAll);
    }

    public void centOsStartDocker(JschUtil jsch) throws JSchException {
        jsch.execute(COMMAND_CENTOS_START_DOCKER, 60000);
    }
}
